/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.security.action.Secure;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.apache.commons.beanutils.PropertyUtils;
import org.xptracker.domain.*;
import org.xptracker.persistence.PersistenceManager;

import java.util.Arrays;
import java.util.List;

public class TimelineActionBean extends StandardActionBean {
  private List<Timeline> timelines;

  @ValidateNestedProperties({
      @Validate(field="name", required=true)})
  private Timeline timeline;
  private List<Queue> queues;
  private List<State> states;
  private Criterion criterion;

  public Timeline getTimeline() { return timeline; }
  public void setTimeline(Timeline timeline) { this.timeline = timeline; }

  public List<Timeline> getTimelines() { return timelines; }
  public void setTimelines(List<Timeline> timelines) { this.timelines = timelines; }

  public Criterion getCriterion() { return criterion; }
  public void setCriterion(Criterion criterion) { this.criterion = criterion; }

  public List<Queue> getQueues() { return queues; }
  public List<State> getStates() { return states; }

  @DefaultHandler
  @DontValidate
  public Resolution displayTimelines() {
    return new ForwardResolution("/timelines.jsp");
  }

  @Secure(roles="admin")
  @HandlesEvent("Delete")
  @DontValidate
  public Resolution deleteTimeline() {
    persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Object>() {
      public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Timeline timeline = domain.loadEntity(Timeline.class, param("id"));
        for(User user: domain.listUsers(true)) {
          if (user.getTimelines().remove(timeline)) {
            receiver.update(user);
          }
        }
        return null;
      }
    });

    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Timeline timeline = domain.loadEntity(Timeline.class, param("id"));
        receiver.remove(timeline);
        addMessage("Timeline ''{0}'' deleted", timeline.getName());
        return new RedirectResolution(TimelineActionBean.class);
      }
    });
  }

  @Secure(roles="admin")
  @HandlesEvent("Add")
  public Resolution addTimeline() {
    if (timeline != null) {
      persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Object>() {
        public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
          Timeline shouldBeNull = domain.loadTimeline(timeline.getName());
          if (shouldBeNull == null) {
            receiver.insert(timeline.getGranularity());
            receiver.insert(timeline);
            addMessage("Timeline added: {0}", timeline.getName());
          } else {
            addError("timeline.name", "Timeline ''{1}'' already exists", timeline.getName());
          }
          return null;
        }
      });
    }
    return new RedirectResolution(getClass()).flash(this);
  }

  @Secure(roles="admin")
  @HandlesEvent("Edit")
  public Resolution editTimeline() {
    if (timeline != null) {
      persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Object>() {
        public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
          Timeline localTimeline = domain.loadEntity(Timeline.class, timeline.getId());
          localTimeline.setName(timeline.getName());
          localTimeline.getGranularity().setInterval(timeline.getGranularity().getInterval());
          localTimeline.getGranularity().setPeriod(timeline.getGranularity().getPeriod());
          localTimeline.setUnits(timeline.getUnits());
          receiver.update(localTimeline);
          addMessage("Timeline updated");
          return null;
        }
      });
    }
    return new RedirectResolution(getClass()).flash(this);
  }

  private interface CriteriaCollector {
    boolean addCriterion(Timeline timeline, Criterion criterion);
  }

  @Secure(roles="admin")
  @HandlesEvent("AddEntryCriterion")
  @DontValidate
  public Resolution addEntryCriterion() {
    return addCriterion(new CriteriaCollector() {
      public boolean addCriterion(Timeline timeline, Criterion criterion) {
        return timeline.addEntryCriterion(criterion);
      }
    });
  }

  @Secure(roles="admin")
  @HandlesEvent("AddExitCriterion")
  @DontValidate
  public Resolution addExitCriterion() {
    return addCriterion(new CriteriaCollector() {
      public boolean addCriterion(Timeline timeline, Criterion criterion) {
        return timeline.addExitCriterion(criterion);
      }
    });
  }

  private Resolution addCriterion(final CriteriaCollector criteriaCollector) {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Timeline timeline = domain.loadEntity(Timeline.class, param("id"));
        Criterion newC = new Criterion();
        try {
          PropertyUtils.copyProperties(newC, criterion);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }

        receiver.insert(newC);
        if (criteriaCollector.addCriterion(timeline, newC)) {
          receiver.update(timeline);
          addMessage("Criterion added: " + criterion);
        } else {
          receiver.remove(newC);
          addGlobalError("Criterion already exists: {1}", criterion);
        }
        return new RedirectResolution(TimelineActionBean.class).flash(TimelineActionBean.this);
      }
    });
  }

  @Secure(roles="admin")
  @HandlesEvent("DeleteCriterion")
  @DontValidate
  public Resolution deleteCriterion() {
    persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Object>() {
      public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Timeline timeline = domain.loadEntity(Timeline.class, param("id"));
        Criterion criterion = domain.loadEntity(Criterion.class, param("cid"));
        timeline.removeCriterion(criterion);
        receiver.remove(criterion);
        receiver.update(timeline);
        addMessage("Criterion removed: " + criterion);
        return null;
      }
    });
    return new RedirectResolution(getClass());
  }

  @Before(stages=LifecycleStage.BindingAndValidation)
  public void provideTimelines() {
    this.timelines = DomainUtil.fullyLoadItems(domain.listTimelines());
    if (timeline == null) {
      this.timeline = new Timeline();
    }
    this.queues = domain.listQueues(false);
    this.states = Arrays.asList(State.values());
    this.criterion = new Criterion();
  }
}
